package vip.ola.code.ctrl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import vip.ola.code.common.ctrl.BaseController;
import vip.ola.code.common.service.RpcCommonService;
import vip.ola.code.secruity.JwtUser;
import vip.ola.core.common.annotation.MethodLog;
import vip.ola.core.common.constant.CodeConstant;
import vip.ola.core.common.constant.Constant;
import vip.ola.core.common.constant.RetEnum;
import vip.ola.core.common.domain.BizResponse;
import vip.ola.core.common.domain.PayResponse;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.entity.code.CodeAccountHistory;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Optional;

import static vip.ola.core.common.constant.CodeConstant.*;
import static vip.ola.core.common.constant.Constant.CODE_ROLE_NORMAL;
import static vip.ola.core.common.util.LocalDateTimeUtil.PATTERN_DATE_TIME;

@RestController
@RequestMapping(Constant.CODE_CONTROLLER_ROOT_PATH + "/accountHistory")
@PreAuthorize("hasRole('" + CODE_ROLE_NORMAL + "')")
public class AccountHistoryController extends BaseController {

    private final MyLog log = MyLog.getLog(AccountHistoryController.class);

    @Autowired
    private RpcCommonService rpcService;

    @RequestMapping("/list")
    public ResponseEntity<?> list(@DateTimeFormat(pattern = PATTERN_DATE_TIME)LocalDateTime startTime, @DateTimeFormat(pattern = PATTERN_DATE_TIME)LocalDateTime endTime,
                                  String username, String orderNo, String bizItem, Integer fundDirection, Integer bizType) {
        CodeAccountHistory history = getAccountHistory();
        history.setUsername(username);
        history.setOrderNo(orderNo);
        history.setBizItem(bizItem);
        history.setFundDirection(fundDirection);
        history.setBizType(bizType);
        history.setCreateTime(startTime);
        history.setUpdateTime(endTime);
        IPage<CodeAccountHistory> page = rpcService.codeAccountHistoryService.list(getPageIndex(), getPageSize(), history);
        return ResponseEntity.ok(PayResponse.buildPageSuccess(page));
    }

    @RequestMapping("/count")
    public ResponseEntity<?> count(@DateTimeFormat(pattern = PATTERN_DATE_TIME)LocalDateTime startTime, @DateTimeFormat(pattern = PATTERN_DATE_TIME)LocalDateTime endTime,
                                   String username, String orderNo, String bizItem, Integer fundDirection, Integer bizType) {
        CodeAccountHistory history = getAccountHistory();
        history.setUsername(username);
        history.setOrderNo(orderNo);
        history.setBizItem(bizItem);
        history.setFundDirection(fundDirection);
        history.setBizType(bizType);
        history.setCreateTime(startTime);
        history.setUpdateTime(endTime);

        Map countMap = rpcService.codeAccountHistoryService.countAll(history);
        Map addMap = rpcService.codeAccountHistoryService.countAdd(history);
        Map subtractMap = rpcService.codeAccountHistoryService.countSubtract(history);

        BigDecimal addTotalAmount = Optional.ofNullable(addMap).map(m -> m.get("totalAmount")).map(Object::toString).map(BigDecimal::new).orElse(BigDecimal.ZERO);
        BigDecimal subTotalAmount = Optional.ofNullable(subtractMap).map(m -> m.get("totalAmount")).map(Object::toString).map(BigDecimal::new).orElse(BigDecimal.ZERO);

        JSONObject obj = new JSONObject();
        obj.put("totalCount", countMap.getOrDefault("totalCount", 0));
        obj.put("totalAmount", countMap.getOrDefault("totalAmount", 0));
        obj.put("addTotalCount", addMap.getOrDefault("totalCount", 0));
        obj.put("addTotalAmount", addTotalAmount);
        obj.put("subTotalCount", subtractMap.getOrDefault("totalCount", 0));
        obj.put("subTotalAmount", subTotalAmount);
        obj.put("surplusTotalAmount", addTotalAmount.add(subTotalAmount));
        return ResponseEntity.ok(PayResponse.buildSuccess(obj));
    }

    private CodeAccountHistory getAccountHistory() {
        JwtUser user = getUser();
        CodeAccountHistory history = new CodeAccountHistory();
        Integer type = user.getType();
        if (CODE_USER_TYPE.equals(type)) {
            history.setUserId(user.getId());
            history.setAgentId(user.getAgentId());
            history.setCodeBusId(user.getCodeBusId());
        } else if (CODE_AGENT_TYPE.equals(type)) {
            history.setAgentId(user.getId());
            history.setCodeBusId(user.getCodeBusId());
        } else if (CODE_CODE_SUB_TYPE.equals(type)) {
            history.setCodeBusId(user.getCodeBusId());
        } else if (CODE_CODE_TYPE.equals(type)) {
            history.setCodeBusId(user.getId());
        }
        return history;
    }

    @RequestMapping("/get")
    @MethodLog(remark = "订单详情")
    public ResponseEntity get(long id) {
        JwtUser user = getUser();
        CodeAccountHistory order = rpcService.codeAccountHistoryService.getById(id);
        if (order == null) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.CODE_ORDER_NOT_EXIST));
        }
        Integer type = user.getType();
        if ((CODE_USER_TYPE.equals(type) && order.getUserId().equals(user.getId()))
                || (CodeConstant.CODE_CODE_SUB_TYPE.equals(type) && order.getCodeBusId().equals(user.getId()))
                || (CODE_CODE_TYPE.equals(type) && order.getCodeBusId().equals(user.getId()))) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.CODE_ORDER_NOT_AUTH));
        }
        return ResponseEntity.ok(PayResponse.buildSuccess(order));
    }

}
